package com.database.service.impl;


import com.database.character.Attention;
import com.database.character.UserAccount;
import com.database.mapper.AttentionMapper;
import com.database.mapper.UserMapper;
import com.database.service.AttentionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AttentionServiceImpl implements AttentionService {

	@Autowired
	private AttentionMapper attentionMapper;

	@Autowired
	private UserMapper userMapper;

	@Override
	public int addAttention(Attention attention) {
		Integer userId = attention.getUserId();
		Integer focusedId = attention.getFocusedId();
		UserAccount userAccount1 = userMapper.getByUid(userId);
		UserAccount userAccount2 = userMapper.getByUid(focusedId);
		userAccount1.setAttentionNum(userAccount1.getAttentionNum() + 1);//用户1关注数加一
		userAccount2.setFocusedNum(userAccount2.getFocusedNum() + 1);//用户2被关注数加一
		userAccount1.setUpdateTime(LocalDateTime.now());//用户1更新时间
		userAccount2.setUpdateTime(LocalDateTime.now());//用户2更新时间
		int i = userMapper.updateUser(userAccount1);
		int i1 = userMapper.updateUser(userAccount2);
		int i2 = attentionMapper.addAttention(attention);
		return i * i1 * i2;
	}

	@Override
	public int deleteByAttentionId(Integer attentionId) {
		Attention attention = attentionMapper.getByAttentionId(attentionId);
		Integer userId = attention.getUserId();
		Integer focusedId = attention.getFocusedId();
		UserAccount userAccount1 = userMapper.getByUid(userId);
		UserAccount userAccount2 = userMapper.getByUid(focusedId);
		userAccount1.setAttentionNum(userAccount1.getAttentionNum() - 1);//用户1关注数减一
		userAccount2.setFocusedNum(userAccount2.getFocusedNum() - 1);//用户2被关注数减一
		userAccount1.setUpdateTime(LocalDateTime.now());//用户1更新时间
		userAccount2.setUpdateTime(LocalDateTime.now());//用户2更新时间
		int i = userMapper.updateUser(userAccount1);
		int i1 = userMapper.updateUser(userAccount2);
		int i2 = attentionMapper.deleteByAttentionId(attentionId);
		return i * i1 * i2;
	}

	@Override
	public List<Attention> getAttentionByUid(Integer userId) {
		return attentionMapper.getAttentionByUid(userId);
	}

	@Override
	public Attention getByUidAndFid(Integer userId, Integer focusedId) {
		return attentionMapper.getByUidAndFid(userId, focusedId);
	}

	@Override
	public int deleteByUidAndFid(Integer userId, Integer focusedId) {
		return attentionMapper.deleteByUidAndFid(userId, focusedId);
	}
}
